package com.service.api;

import java.net.URI;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.handler.codec.http.CookieEncoder;
import org.jboss.netty.handler.codec.http.DefaultHttpRequest;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.codec.http.HttpVersion;

public class HttpClient {

	public void doRequest(String Uri,BaiduApiServer server) throws Exception {
		URI localURI = new URI(Uri);
		String str1 = (localURI.getScheme() == null) ? "http" : localURI.getScheme();
		String ip = (localURI.getHost() == null) ? "localhost" : localURI.getHost();
		int port = localURI.getPort();
		if (port == -1)
			if (str1.equalsIgnoreCase("http")){
				port = 80;
			}
			else if (str1.equalsIgnoreCase("https")){
				port = 443;
			}
		if ((!(str1.equalsIgnoreCase("http"))) && (!(str1.equalsIgnoreCase("https")))) {
			System.err.println("Only HTTP(S) is supported.");
			return;
		}


		Channel localChannel = CacheManager_app.instance().getActiveChannel(ip, port);
		CacheManager_app.instance().appMap.put(localChannel.getId(), server);

		DefaultHttpRequest localDefaultHttpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, localURI.toASCIIString());
		localDefaultHttpRequest.setHeader("Host", ip);
		localDefaultHttpRequest.setHeader("Connection", "close");
		localDefaultHttpRequest.setHeader("Accept-Encoding", "gzip");
		CookieEncoder localCookieEncoder = new CookieEncoder(false);
		localCookieEncoder.addCookie("my-cookie", "foo");
		localCookieEncoder.addCookie("another-cookie", "bar");
		localDefaultHttpRequest.setHeader("Cookie", localCookieEncoder.encode());
		//写完
		localChannel.write(localDefaultHttpRequest);
		//等待关闭
		localChannel.getCloseFuture().awaitUninterruptibly();

		CacheManager_app.instance().appMap.remove(localChannel.getId());
	}
}
